import { useState } from "react";

import { FCForm, FCTable } from "@components";
import ModalComponent from "./components/modal";

/**
 * 
 * @param formProps  查询表单配置
 * @param tableProps  表格配置
 * @param queryApi  查询接口
 * @param defaultPagiProps  分页默认配置
 * @param showModal  是否需要modal
 * @param modalRef  modal ref
 * @param modalFormProps  modal 表单props
 * @param updataId  主键id
 * @param addApi  新增接口
 * @param updataApi  新增编辑接口
 * @returns 
 */

const QueryPage = (props) => {
  const {
    formProps,
    tableProps,
    queryApi,
    defaultPagiProps = { current: 1, pageSize: 20 },
    showModal= true,
    modalRef,
    modalFormProps,
    addApi,
    updataId,
    updataApi,
  } = props;

  const queryFormRef = formProps.formRef
  const [dataSource, setDataSource] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagiProps, setPagiProps] = useState(defaultPagiProps);

  const getDataSource = async (params) => {
    setLoading(true);

    const { data, error } = await queryApi(params);
    setLoading(false);

    if (error) return; setDataSource([]);
    setPagiProps({ ...pagiProps, current: data.currentPage, total: data.totalCount, pageSize: data.pageSize });
    setDataSource(data.pageList);
  };

  const initFormProps = {
    name: "queryForm",
    layoutProps: {
      layout: "grid",
      gridConfig: { colCount: 3 },
    },
    onFinish: (params) => {
      if (loading) return;
      const {pageSize, current: currentPage} = defaultPagiProps
      getDataSource({ queryDto: { ...params }, currentPage, pageSize });
    },
    submitButton: { show: true, icon: "SearchOutlined" },
    resetButton: { show: true, icon: "UndoOutlined" },
    ...formProps
  };

  const onTableChange = ({ pagination }) => {
    const {pageSize, current: currentPage} = pagination
    const params = queryFormRef.current.getFieldsValue()
    getDataSource({ queryDto: { ...params }, currentPage, pageSize  })
  };

  const initTableProps = {
    isConfig: false,
    loading: loading,
    dataSource: dataSource,
    pagination: pagiProps,
    onTableChange,
    ...tableProps
  };

  return (
    <div className={`page-content`}>
      <FCForm {...initFormProps} />
      <FCTable {...initTableProps} />
      {showModal && <ModalComponent
        modalRef={modalRef}
        queryFormRef={queryFormRef}
        modalFormProps={modalFormProps}
        addApi={addApi}
        updataId={updataId}
        updataApi={updataApi}
      />}
    </div>
  );
};

export default QueryPage;
